//
//  MerchantManagerViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/10/17.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "MerchantManagerViewController.h"
#import "ShopListTableViewCell.h"
#import "ShopAndOpenListModel.h"
#import "ShopAndOpenInforModel.h"
#import "BaseSearchChooseViewController.h"
#import "ChooseListModel.h"
#import "GetRegisterInforModel.h"
#import "ShopRegisterViewController.h"
#import "GotoCheckViewController.h"
#import "StoreHomeViewController.h"
#import "SubjectListViewController.h"
@interface MerchantManagerViewController ()

@property(nonatomic,strong)ShopAndOpenInforModel *InforModel;

@property(nonatomic,copy)NSString*SearchKeyWord;

@end

@implementation MerchantManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.homeTableView.estimatedRowHeight=60;
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"ShopListTableViewCell" bundle:nil] forCellReuseIdentifier:@"Shopcell"];
    
    [self.homeTableView.mj_header beginRefreshing];
    // Do any additional setup after loading the view.
}

#pragma mark-tablevie代理方法


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShopAndOpenData *model=self.dataArr[indexPath.row];
    
    ShopListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Shopcell" forIndexPath:indexPath];
    
    cell.isClick=self.isEdit;
    
    cell.deleStatue=self.deleStatue;//是否编辑状态
    
    cell.model=model;
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isdeleMore) {

        if (self.deleStatue) {
            
            ShopAndOpenData *data=self.dataArr[indexPath.row];
            
            data.Seleclt=!data.Seleclt;
            
            [self ChangeStatues];
            
            [self.homeTableView reloadData];
      
        }else{
            
            if (self.pushType==0) {
                //跳转商户首页
                
                 ShopAndOpenData *data=self.dataArr[indexPath.row];
                
                StoreHomeViewController *storeHome=[StoreHomeViewController new];
                
                storeHome.shopid=data.shopId;
                
                [self.navigationController pushViewController:storeHome animated:YES];
                
            }
        }
        
    }else{
    
        if (self.pushType==1)
        {
            //去检查
           ShopAndOpenData *data=self.dataArr[indexPath.row];
            JobListModel *list=[JobListModel new];
            
            list.type=self.Reqmodel.type;
            
            list.ptype=@"1";
            
            SubjectListViewController *shopsubject=[SubjectListViewController new];
            
            shopsubject.reqModel=list;
            
            shopsubject.Tiptitle=data.shopName;
            
            shopsubject.objId=[NSString stringWithFormat:@"%ld",data.shopId];
            
            [self.navigationController pushViewController:shopsubject animated:YES];
            
        }else{
            
            
            ShopAndOpenData *data=self.dataArr[indexPath.row];
            
            StoreHomeViewController *storeHome=[StoreHomeViewController new];
            
            storeHome.shopid=data.shopId;
            
            [self.navigationController pushViewController:storeHome animated:YES];
            
        }
       
            
   
    }
    
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isEdit) {
        
        return YES;
    }
    
    return NO;
    
}


-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return @"删除";
    
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        
        ShopAndOpenData *data=self.dataArr[indexPath.row];
        
        NSMutableArray *arr=[NSMutableArray array];
        
        [arr addObject:[NSString stringWithFormat:@"%ld",data.shopId]];
        
        [self DelPostion:arr];
        
    }
    
}


-(void)DelPostion:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/shopDel.json" andrequestTime:5 andParams:@{@"shopIds":params} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"删除成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            if (self.deleStatue) {
                //如果处于删除状态
                [self GotoEdit:self.btn];
            }
            
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}


#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
    //去筛选搜索
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:ShopListType];
    
    Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:ShopListType andIsLookSelf:YES];
    
    Choose.paradic=[SearchAndChooseManager getChooseParaWithType:ShopListType andType:self.Reqmodel.type];
    
    Choose.SearchPlace=self.searchName;
    
     Choose.KeyWord=self.SearchKeyWord;

    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
   
        
        self.Reqmodel.params=paras;
        
        self.SearchKeyWord=keyword;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}
#pragma mark-编辑事件
-(void)GotoEdit:(UIButton*)sender
{
    sender.selected=!sender.selected;
    
    self.deleStatue=sender.selected;
    
    if (!self.deleStatue) {
        
        for (ShopAndOpenData *data in self.dataArr) {
            
            data.Seleclt=NO;
            
        }
        
        [self ChangeStatues];
    }
    
    [self.homeTableView reloadData];
}


-(void)SeletAll
{
    
    for (ShopAndOpenData *data in self.dataArr) {
        
        data.Seleclt=YES;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//全选

-(void)CanseletAll{
    
    for (ShopAndOpenData *data in self.dataArr) {
        
        data.Seleclt=NO;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//取消全选

-(void)DelectAll
{
    NSMutableArray *arr=[NSMutableArray array];
    
    for ( ShopAndOpenData *data in self.dataArr) {
        
        if (data.Seleclt) {
            
            [arr addObject:[NSString stringWithFormat:@"%ld",data.shopId]];
            
        }
        
    }
    
    if (arr.count==0) {
        
        [MBProgressHUD showWarnMessage:@"请至少选择一项"];
        
        return;
    }
    
    [self DelPostion:arr];
}//全部删除


-(void)ChangeStatues{
    
    NSInteger i=0;
    
    for (ShopAndOpenData *data in self.dataArr) {
        
        if (data.Seleclt) {
            i++;
        }
    }
    
    [self.DeleView SelectNum:i];
}

#pragma mark-新增事件
-(void)addNewgoods
{
    //新增商品
   
    
    if ([self getUserType]==2||[self getUserType]==4) {
        
        //检查员注册商户
        GotoCheckViewController *GotoCheck=[GotoCheckViewController new];
        
        GotoCheck.userType=0;
        
        GotoCheck.RegisterPeople=2;
        
        [self.navigationController pushViewController:GotoCheck animated:YES];
        
    }else{
        
        //开办方注册商户
        
        GetRegisterInforModel *shopmodel=[GetRegisterInforModel new];
        
        shopmodel.type=[NSString stringWithFormat:@"%ld",[LoginStatuesModel shoptype]];
        
        shopmodel.token=[LoginStatuesModel getUserToken];
     
        shopmodel.marketId=[NSString stringWithFormat:@"%ld",[LoginStatuesModel getStaffId]];
    
        ShopRegisterViewController *ShopRegister=[ShopRegisterViewController new];
        
        ShopRegister.requrl=@"/index.php/FoodCheckApi/shopRegInfo.json";
        
        ShopRegister.Reqmodel=shopmodel;
        
        ShopRegister.postUrl=@"/index.php/FoodCheckApi/shopReg.json";
        
        ShopRegister.title=@"商户注册";
        
        ShopRegister.BtnStr=@"注册";
        
        ShopRegister.OptionSussStr=@"注册成功";
        
        ShopRegister.block=^()
        {
            
            [self.homeTableView.mj_header beginRefreshing];
        };
        
        [self.navigationController pushViewController:ShopRegister animated:YES];
    }
    
    
  
    
}

#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    
    [self loadDatas];
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/shopList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
       self.InforModel=[ShopAndOpenInforModel mj_objectWithKeyValues:responseObject];
 
        if (responseStatus==1) {
            //请求成功
            
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@", self.InforModel.totalRecord,@"商户"];
            
            if (self.InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                [self.homeTableView reloadData];
                
                self.Type=TBNODateType;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                self.btn.hidden=YES;
            }else if (self.InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray: self.InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
